import appStorage from '@/utils/store/index'
import {
	safeJsonStringInBrowser
} from "@/utils/libs/data";

const Storage: any = new appStorage()

export default class $http {
	public config: any;
	constructor (config: any) {
		this.config = config
	}
	/**
	* @description 开始请求
	*/
	public request (options: any): any {
		console.log('--------', this.config)
		// 默认request配置
		const config: any = {
			//baseUrl: options.baseUrl || this.config.ip[process.env.NODE_ENV === 'development' ? 'development' : 'production'],
			baseUrl: options.baseUrl || this.config.ip.app,
			header: {
				'Content-Type': 'application/json;charset=UTF-8'
			},
			data: {},
			method: "GET",
			dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
			responseType: "text",
			success() { },
			fail() { },
			complete() { }
		}
		// 拦截器相关
		const interceptor = {
			request: null,
			response: null
		}
		
		if (!options) options = {}
		options = {
			...options,
			baseUrl: options.baseUrl || config.baseUrl,
			dataType: options.dataType || config.dataType,
			url: options.url.includes('com') && options.url.includes('http') ? options.url : config.baseUrl + options.url,
			data: options.data || {},
			method: options.method || config.method
		}
		// token及自定义header
		options.header = Object.assign({}, options.header, this.config.request.headers, {
			Authorization: options.token ? `Bearer ${options.token}` : `Bearer ${uni.getStorageSync('token')}`
		})
		
		return new Promise((resolve: any, reject: any): any => {
			let _config: any = null
			// 响应相关
			options.complete = (res: any) => {
		        if (options.custom) {
		            // 兼容su部分接口返回data为空的情况
		            resolve(res)
		            return false
		        }
				if (typeof (res) === 'object') {
					res = JSON.stringify(res)
					res = JSON.parse(safeJsonStringInBrowser(res, true))
				}
				res.config = _config
		        if (res.errMsg && res.errMsg.indexOf('-1') !== -1) {
		            uni.showToast({
		            	title: res[this.config.response.dataName].message || '服务器开小差了',
		            	icon: 'none'
		            })
		            reject(res)
		            return false
		        }
		        if (res.errMsg && res.errMsg.indexOf('timeout') !== -1) {
		            uni.showToast({
		            	title: '请求超时',
		            	icon: 'none'
		            })
		            reject(res)
		            return false
		        }
				if (res.statusCode === 200) {
					// 兼容su部分接口返回data为空的情况
					if (res.data.status === 401) {
						uni.navigateTo({
							url: '/pages/auth/login'
						})
						return false
					}
					if (res.data.status === 200) {
						resolve(res[this.config.response.dataName])
					} else {
						uni.showToast({
							title: res[this.config.response.dataName].msg,
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: res[this.config.response.dataName].msg,
						icon: 'none'
					})
					resolve(res[this.config.response.dataName])
				}
				// 拦截response
				if (interceptor.response) {
					let newResponse = interceptor.response(res)
					if (newResponse) {
						res = newResponse
					}
				}
			}
			// 请求相关
			_config = Object.assign({}, config, options)
			_config.requestId = new Date().getTime()
			if (interceptor.request) {
				interceptor.request(_config)
			}
			uni.request(_config)
		})
	}
	/**
	* @description get
	*/
	public get (url: any, data?: any, options?: any) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	}
	/**
	* @description post
	*/
	public post(url: any, data?: any, options?: any) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}
	/**
	* @description put
	*/
	public put(url: any, data?: any, options?: any) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	}
	/**
	* @description delete
	*/
	public delete(url: any, data?: any, options?: any) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}